package io.jft.doll.tcp.handle

import com.g.base.help.d
import com.g.base.token.TokenManage
import io.jft.doll.tcp.TcpC
import io.jft.doll.tcp.TcpC.Companion.COMD_REP_HEART
import io.jft.doll.tcp.TcpC.Companion.COMD_REP_LOGIN
import io.jft.doll.tcp.TcpC.Companion.HEART_BEAT
import io.jft.doll.tcp.TcpClient
import io.jft.doll.tcp.event.TcpData
import io.jft.doll.tcp.tcpClient
import io.jft.doll.tcp.utils.BytesUtil
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.SimpleChannelInboundHandler
import io.netty.handler.timeout.IdleState
import io.netty.handler.timeout.IdleStateEvent
import org.greenrobot.eventbus.EventBus

/**
 * Created by G on 2017/12/25 0025.
 */
class BusinessHandle : SimpleChannelInboundHandler<TcpData>() {
    private var missHeartCount = 0

    override fun channelActive(ctx: ChannelHandlerContext) {
        d("tcp channelActive")
        tcpClient.status = TcpClient.ConnectStatus.Connected
        val token = TokenManage.getToken()
        if (token == null) {
            tcpClient.disConnect()
        }
        val buffer = tcpClient.createBuffer()
        buffer.writeBytes(BytesUtil.hexStringToBytes(token?.token))
        tcpClient.writeAndFlush(TcpData(TcpC.COMD_LOGIN, buffer), false) {}
    }

    override fun exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable) {
        d("tcp exceptionCaught ${cause.message}}")
        tcpClient.status = TcpClient.ConnectStatus.Offline
        ctx.disconnect()
    }

    override fun channelInactive(ctx: ChannelHandlerContext) {
        d("tcp channelInactive")
        tcpClient.status = TcpClient.ConnectStatus.Offline
        tcpClient.connect()
    }

    override fun channelRead0(ctx: ChannelHandlerContext, msg: TcpData) {
        //收到包清空心跳丢失
        missHeartCount = 0
        when (msg.command) {
            COMD_REP_LOGIN -> {
                tcpClient.status = TcpClient.ConnectStatus.Login
            }
            COMD_REP_HEART -> {
            }
            else -> EventBus.getDefault().post(msg)
        }
    }

    override fun userEventTriggered(ctx: ChannelHandlerContext, evt: Any) {
        super.userEventTriggered(ctx, evt)
        if (evt is IdleStateEvent && evt.state() == IdleState.ALL_IDLE) {
            missHeartCount++
            tcpClient.writeAndFlush(HEART_BEAT, false) {}
            d("tcp sendHeader missHeaderCount: $missHeartCount")
            if (missHeartCount > 3) {
                d("tcp outOfConnect")
                ctx.disconnect()
            }
        }
    }
}